# !/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# @Time: 2021/3/28 01:00

import random

import requests
import hashlib
from log.logger import logger
from proxy.proxy import my_proxy
from datetime import datetime
import functools
import schedule


USER_AGENTS =  [
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 OPR/26.0.1656.60',
		'Opera/8.0 (Windows NT 5.1; U; en)',
		'Mozilla/5.0 (Windows NT 5.1; U; en; rv:1.8.1) Gecko/20061208 Firefox/2.0.0 Opera 9.50',
		'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; en) Opera 9.50',
		'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0',
		'Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10',
		'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2 ',
		'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36',
		'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
		'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16',
		'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36',
		'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko',
		'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11',
		'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER',
		'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)',
		'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 SE 2.X MetaSr 1.0',
		'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; SE 2.X MetaSr 1.0) ',
    ]
weibo_cookies = ''

def get_random_useragent():
    return random.choice(USER_AGENTS)


def requests_get(url, module_name='未指定', headers=None, params=None, use_proxy=False,cookies=None):
    if headers is None:
        headers = {}
    headers = dict({
        'User-Agent': get_random_useragent()
    }, **headers)
    proxies = _get_proxy() if use_proxy else None
    try:
        response = requests.get(url, headers=headers, params=params, proxies=proxies, timeout=10,cookies=cookies)
    except Exception as e:
        logger.error("【{}】：{}".format(module_name, e))
        return None
    return response


def requests_post(url, module_name='未指定', headers=None, params=None, data=None, json=None, use_proxy=False,cookies=None):
    if headers is None:
        headers = {}
    headers = dict({
        'User-Agent': get_random_useragent()
    }, **headers)
    proxies = _get_proxy() if use_proxy else None
    try:
        response = requests.post(url, headers=headers, params=params, data=data, json=json, proxies=proxies, timeout=10,cookies=cookies)
    except Exception as e:
        logger.error("【{}】：{}".format(module_name, e))
        return None
    return response


def _get_proxy():
    if my_proxy.enable == 'true':
        proxy_ip = my_proxy.current_proxy_ip
        if proxy_ip is None:
            return None
        else:
            return {
                "http": "http://{}".format(proxy_ip)
            }


def check_response_is_ok(response=None):
    if response is None:
        return False
    if response.status_code != requests.codes.OK:
        logger.error('status: {}, url: {}'.format(response.status_code, response.url))
        return False
    return True


def hash_file(file_name):
    m = hashlib.md5()
    with open(file_name, 'rb') as fh:
        while True:
            data = fh.read(8192)
            if not data:
                break
            m.update(data)
        hash_value = m.hexdigest()
    return hash_value


def weekday():
    week_list = ["星期一","星期二","星期三","星期四","星期五","星期六","星期日"]
    return week_list[datetime.today().weekday()]

def catch_exceptions(cancel_on_failure=False):
    def catch_exceptions_decorator(job_func):
        @functools.wraps(job_func)
        def wrapper(*args, **kwargs):
            try:
                return job_func(*args, **kwargs)
            except:
                import traceback
                logger.info('捕获全局异常:'+traceback.format_exc())
                if cancel_on_failure:
                    return schedule.CancelJob
        return wrapper
    return catch_exceptions_decorator


